package com.mao.service.impl;


import com.alibaba.fastjson.JSONObject;
import com.mao.entity.SecurityUser;
import com.mao.entity.User;
import com.mao.entity.UserSecurity;
import com.mao.service.PermissionService;
import com.mao.service.UserService;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.BeanFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.List;

/**
 * @author Mr.Mao
 */
@Service("userDetailsService")
public class UserDetailsServiceImpl implements UserDetailsService {

    @Autowired
    private UserService userService;

    @Autowired
    private PermissionService permissionService;

    /**
     *
     * @param username
     * @return
     * @throws UsernameNotFoundException
     */
    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {

        // 根据用户名查询数据库

        User user = userService.selectByUsername(username);

        if (user == null){
            throw new UsernameNotFoundException("用户不存在");
        }

        UserSecurity curUser = new UserSecurity();
        BeanUtils.copyProperties(user,curUser);

        // 根据用户查询权限信息
        List<String> permissionValueList = permissionService.selectPermissionValueByUserId(user.getId());

        SecurityUser securityUser = new SecurityUser();
        securityUser.setPermissionValueList(permissionValueList);

        return securityUser;
    }
}
